package org.imlinker.plugin;

import java.io.File;
import java.util.ArrayList;

import org.imlinker.buddy.ChatAdapter;
import org.imlinker.login.Core;

import org.jivesoftware.smack.XMPPConnection;

public class PluginManager {

	public PluginManager(final String paraPath) {
		this.path = paraPath;

		ResourceManager.setPath(paraPath);
	}

	public ArrayList<String> getNameList() {
		return infoList;
	}

	public void startPlugin(String name) {

		if (list.size() > 0 && list.get(0).getName().equalsIgnoreCase(name)) {
			list.get(0).openPlugin(true);
		}
	}

	/**
	 * 初始化，把 plugin /文件夹里的插件导入到 plugin 列表里.
	 */
	public void initial() {

		File pluginDir = new File(path + File.separator + "plugin");

		// 确定文件夹没有错
		if (pluginDir != null && pluginDir.isDirectory()) {
			File[] files = pluginDir.listFiles();
			for (File f : files) {
				// 跳过非.jar文件
				String name = f.getName();
				if (!name.endsWith(".jar")) {
					continue;
				}

				infoList.add(name.substring(0, name.length() - 4));
			}
		}

		for (String name : infoList) {

			try {
				Class<?> pluginClass = Class.forName("org.imlinker.plugin."
						+ name);

				PluginItem item = new PluginItem(name, pluginClass);
				list.add(item);

			} catch (ClassNotFoundException e) {
				System.out.println("Plugin:" + name + " failed");
			}

		}
		// displayList.addElement(new PluginItem(null,"Say",Say.class));
		Core.save();
	}

	public void setConnetion(XMPPConnection newConnection) {
		ResourceManager.setConnection(newConnection);
	}

	public void setAdapter(ChatAdapter adapter) {
		ResourceManager.setAdapter(adapter);
	}

	private ArrayList<PluginItem> list;

	private ArrayList<String> infoList = new ArrayList<String>();

	private String path;

}
